<?php


namespace common\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\data\Pagination;

class User extends ActiveRecord
{
    const STATUS_NOT_DEL = 0;
    public $exportNum =[
        1 => 100,
        2 => 200,
        3 => 500,
        4 => 1000,
    ];
    public $code;//数据库中没有的字段
    // 私有，防止被外部代码篡改
    private $pagination;
    /**
     * 获取$pagination，提供给外部代码调用
     * @return mixed
     */
    public function getPagination()
    {
        return $this->pagination;
    }
    /**
     *  校验
     * @create_date 2018/11/12
     * @author quyuanyuan
     */
    public function rules()
    {
        return [
            ['mobile', 'required', 'message' => '请先填写手机号码'],
            ['password', 'required', 'message' => '{attribute}不能为空','on' => 'passLogin'],
            ['mobile', 'checkMobile'],
            ['password', 'string', 'length' => 32, 'tooLong' => '{attribute}不正确','on' => 'passLogin'],
            //添加时验证
            ['mobile', 'required', 'message' => '请先填写手机号码', 'on' => 'addCode'],
            ['code', 'required', 'message' => '请先填写短信验证码', 'on' => 'addCode'],
            //添加用户
            [['password','password_salt', 'username', 'login_error_num', 'last_login_time', 'last_login_ip', 'channel_id','is_del', 'create_time'], 'safe'],


        ];
    }

    /**
     * 设置字段名称
     * @create_date 2018/11/09
     * @author quyuanyuan
     */
    public function attributeLabels()
    {
        return [
            'mobile' => '手机号码',//id为数据表中的字段名，ID 为表单显示的描述
            'password' => '密码',
            'code' => '验证码'
        ];
    }

    /**
     * 验证手机号是否正确
     *
     * @create_date 2018/11/14
     * @author quyuanyuan
     */
    public function checkMobile($attribute, $params)
    {
        if (!check_mobile_number($this->$attribute)) {

            $this->addError($attribute, '请输入正确的手机号');
        }

    }

    /**
     * 验证登录密码是否正确
     * @create_date 2018/11/10
     * @author quyuanyuan
     */
    public function checkPassword($userPassword, $password, $salt = '')
    {
        if (pwd_md5($password, $salt) === $userPassword) {
            return true;
        }
        return false;
    }

    /**
     * 用户是否存在
     * @param int $mobile 手机号
     * @param int $appId 贷超id
     * @return array
     *
     * @create_date 2018/11/10
     * @author quyuanyuan
     */
    public function getOne($mobile, $appId)
    {
        return $query = self::find()->asArray()->where([
            'mobile' => $mobile,
            'app_id' => $appId,
            'is_del' => 0
        ])->one();

    }


    /*
    * 添加用户
    * @create_date 2018/11/10
    * @author quyuanyuan
   */
    public function add($data)
    {

        $this->setAttributes($data,false);
        return $this->save();
    }

    /**
     *插入数据前自动处理添加时间
     *
     * @author yuyan
     * @create_time 2018-11-13
     * */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->create_time = date('Y-m-d H:i:s');
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 分页获取用户列表
     * @param 	mixed 	$where
     * @param 	mixed 	$fields
     * @param 	string 	$order
     * @param 	int 	$page
     * @param 	int 	$limit
     * @return array
     *
     * @create_date 2018-11-17
     * @author quyuanyuan
     */

    public function getUserList($where, $fields = '*', $order = 'create_time desc', $page = 1, $limit = 10)
    {

        $count = self::find()->where($where)->count();

        $paginationObj = new Pagination([
            'totalCount' => $count,
            'pageSize'=> $limit
        ]);

        $list = [];
        if($page <= $paginationObj->pageCount){
            $list = self::find()->select($fields)->where($where)->orderBy($order)->offset($paginationObj->offset)->limit($paginationObj->limit)->asArray()->all();
        }

        return array(
            'page'     => intval($page),
            'count'    =>   intval($paginationObj->totalCount),
            'pageSize' =>  intval($paginationObj->pageSize),
            'list'     => $list ? : []
        );

    }

    /*
    * 用户详情
    * @create_date 2018/11/12
    * @author quyuanyuan
   */
    public function details($userId,$fields = '')
    {

        $where = [
            'id' => $userId,
            'is_del' => 0
        ];
        if(!$fields){
            $fields = ['id', 'user_no', 'app_id', 'username', 'mobile', 'last_login_time','create_time','status'];
        }
        $info = self::find()->select($fields)->where($where)->asArray()->one();
        if($info){
            return $info;
        }

        return false;

    }

    /*
   * 是否屏蔽用户
   * @create_date 2018/11/12
   * @author quyuanyuan
   */
    public function isShieldUser($userId)
    {
        return $query = self::find()->asArray()->where([
            'id' => $userId
        ])->one();
    }

    /*
   * 修改用户
   * @create_date 2018/11/12
   * @author quyuanyuan
   */
    public function edit($data)
    {
        $detail = self::findOne($data['id']);
        $detail->setAttributes($data);
        return $detail->update();
    }

    /*
     * 生成token 32位
     * @param  $info 数组
     *
     * @create_date 2018/11/10
     * @author quyuanyuan
    */
    public function getUserToken($info)
    {
        return md5($info['mobile'] . '|' . strtotime($info['create_time']) . '|' . $info['id'] . '|' . time());
    }

    /*
     * 前台用户token 缓存
     *
     * @param  $cacheKey
     * @param  数组  $userInfo 用户基本信息
     *
     * @create_date 2018/11/13
     * @author quyuanyuan
    */
    public function setUserToken($cacheKey, $userInfo)
    {
        $redis = Yii::$app->redis;
        $redis->set($cacheKey,serialize($userInfo));
        return $redis->expire($cacheKey,30*24*60*60);
    }

    /**
     * 校验用户是否已经登录
     * @desc 已登录返回用户唯一标识ID，否则返回false
     * @param  string $token 用户登录token
     * @param   int $deviceId 设备id
     * @return bool|int
     *
     * @create_date 2018-11-13
     * @author wenqiang
     */
    public function checkUserIsLogin($token, $deviceId = '')
    {
        $redis = Yii::$app->redis;
        $preFix = Yii::$app->params['frontend_user_token_prefix'];
        $userInfo = unserialize($redis->get($preFix . $token));
        if ($userInfo && !empty($userInfo['id'])) {
            // 刷新用户token过期时间
            $redis->set($preFix . $token, serialize($userInfo) );
            $redis->expire($preFix . $token,30*24*60*60);
            return $userInfo['id'];
        } else {
            return false;
        }
    }

    /**
     * 前台用户id token 缓存
     * @param $cacheUserKey 前缀加用户id
     * @param $token 用户token
     * @return mixed
     */
    public function setUserIdToken($cacheUserKey,$token){
        $redis = Yii::$app->redis;
        $redis->set($cacheUserKey,$token);
        return $redis->expire($cacheUserKey,30*24*60*60);
    }

    /**
     * 前台用户删除 该用户的上一个token
     * @param $userId 用户id
     * @return mixed
     */
    public function CheckUserToken($userId){

        $redis = Yii::$app->redis;
        $preFix = Yii::$app->params['frontend_user_token_prefix'];
        $userInfo = $redis->get($preFix.$userId);
        if($userInfo){
            $redis->del($preFix.$userInfo);
        }
    }

    /**
     * 分页获取用户列表
     * @param 	mixed 	$where
     * @param 	mixed 	$fields
     * @param 	string 	$order
     * @return array
     *
     * @create_date 2018-11-27
     * @author quyuanyuan
     */

    public function getUserListAll($where, $fields = '*', $order = 'create_time desc')
    {
        $list = self::find()->select($fields)->where($where)->orderBy($order)->asArray()->all();

        return $list;

    }

    /**
     * @param $where
     * @param string $fields
     * quyuanyuan
     * 2019-01-05
     */
    public function getUserInfo($where,$fields = '*')
    {
        return  self::find()->select($fields)->where($where)->asArray()->one();
    }

    /**
     * 生成用户唯一编号
     * quyuanyuan
     * 2019-0-09
     */
    public function getUserNO()
    {
        $userNo = date('m') . substr(strval(rand(1000000, 9999999)), 0, 6) . rand(11, 99);
        return $userNo;
    }

    /**
     * 清除上次用户登录token
     * @param $userId 用户id
     * @param $token
     * @return mixed
     */
    public function delCacheUserId($userId,$token){
        $redis = Yii::$app->redis;
        $preFix = Yii::$app->params['frontend_user_token_prefix'];
        $userInfo = $redis->get($preFix.$userId);
        if($userInfo){
            $redis->del($preFix.$userInfo);
        }
        $cacheUserKey = \Yii::$app->params['frontend_user_token_prefix'].$userId;
        $redis->set($cacheUserKey,$token);
        return $redis->expire($cacheUserKey,30*24*60*60 );

    }



}